<?php

namespace app\admin\controller\subject;

// 引入基类控制器
use app\common\controller\Backend;

class Chapter extends Backend
{
    // 设置关联查询
    protected $relationSearch = true;

    // 当前模型
    protected $model = null;

    // 无需登陆
    protected $noNeedLogin = [];
    // 无需鉴权
    protected $noNeedRight = [];

    public function __construct(){
        parent::__construct();
        
        $this->model = model('Subject.Chapter');
        $this->SubjectModel = model('Subject.Subject');
    }

    public function index($ids=NULL){

      $subject = $this->SubjectModel->find($ids);
      // var_dump($subject);
      // exit;

      if(!$subject){
          $this->error(__('No Results were found'));
          exit;
      }
      // 接收请求，查询数据
      // 判断是否有ajax请求

      //将请求当中所有的参数去除html标签，去掉两边空白
      $this->request->filter(['strip_tags', 'trim']);

      if($this->request->isAjax()){
          //获取表格所提交过来筛选和排序的一些参数
          list($where, $sort, $order, $offset, $limit) = $this->buildparams();

          // 表格需要两个返回值参数 总条数和分页的数据
          $total = $this->model
              ->with(['subject'])
              ->where($where)
              ->where(['subid'=>$ids])
              ->order($sort,$order)
              ->count(); //返回查询的总数

          // var_dump($total);
          // exit;
          $list = $this->model
              ->with(['subject'])
              ->where($where)
              ->where(['subid'=>$ids])
              ->order($sort,$order)
              ->limit($offset,$limit)
              ->select();
          // var_dump(collection($list)->toArray());
          // exit;

          // 打印sql语句
          // echo $this->model->getLastSql();
          // exit;

          // 组装数据
          $result = [
              'total' => $total,
              'rows' => $list
          ];
          // 返回给ajax的数据
          return json($result);  

      }
      return $this->view->fetch();
    }

    public function add($ids=NULL){
      $subject = $this->SubjectModel->find($ids);
      // var_dump($subject);
      // exit;

      if(!$subject){
          $this->error(__('No Results were found'));
          exit;
      }

      // 接收post请求
      if($this->request->isPost()){
          $params = $this->request->param('row/a');
          // var_dump($params);
          // exit;

          // 组装数据
          $data = [
              'title' => $params['title'],
              'url' => $params['url'],
              'subid' => $ids
          ];
          // var_dump($data);
          // exit;
          // 插入数据库中
          $result = $this->model->validate('common/Subject/Chapter')->save($data);

          if($result === FALSE){
              $this->error($this->model->getError());
              exit;
          }else{
              $this->success('添加章节成功');
              exit;
          }

      }
      // 先将课程章节分类查询出来
      $sublist = $this->SubjectModel->column('id,title');
      $this->assign('sublist',build_select('row[subid]',$sublist,[],['class'=>'selectpicker','required'=>'']));
      return $this->view->fetch();
    }

    public function edit($ids=NULL){
        // 根据id判断要编辑的数据是否存在
        $row = $this->model->find($ids);
        if(!$row){
            $this->error(__('No Results were found'));
            exit;
        }
        // var_dump($row['subid']);
        // exit;

        // 接收post请求
        if($this->request->isPost()){
            $params = $this->request->param('row/a');
            // var_dump($params);
            // exit;
            // 组装数据
            $data = [
              'id' => $ids,
              'title' => $params['title'],
              'url' => $params['url'],
              'subid' => $row['subid']
            ];



            // 更新数据
            $result = $this->model->validate('common/Subject/Chapter')->isUpdate(true)->save($data);


            if($result === FALSE){
                $this->error($this->model->getError());
                exit;
            }

            // 判断是否有新图片上传
            if($data['url'] != $row['url']){
                is_file(".".$row['url']) && @unlink(".".$row['url']);
            }

            $this->success('编辑成功');
            exit;
        }

        // 先将课程章节分类查询出来
      $sublist = $this->SubjectModel->column('id,title');
      $this->assign('sublist',build_select('row[subid]',$sublist,[],['class'=>'selectpicker','required'=>'']));

        $this->assign('row',$row);

        return $this->view->fetch();
    }

    public function del($ids=NULL){
      $list = $this->model->select($ids);
      // var_dump($list);
      // exit;

      // 没有数据
      if(!$list){
          $this->error(__('No Results were found'));
          exit;
      }

      // 删除视频
      // 从数据中提取出url这个字段的值
      $url = array_column($list,"url");

      // 去重、去空
      $url = array_filter($url);
      $url = array_unique($url);
      // 删除
      $result = $this->model->whereIn('id',$ids)->delete(true);
      
      if($result === FALSE){
          $this->error("删除失败");
          exit;
      }else{
          // 删除视频
          if(!empty($url)){
            foreach($url as $item){
                is_file(".".$item) && @unlink(".".$item);
            }
        }
          $this->success("删除成功");
          exit;
      }
  }
}
